// pages/xuexi/lianxi.js
const app = getApp();
const s = new app.Shuju();
var nandu = "";
var nowidx = 0;
const recorderManager = wx.getRecorderManager();
var zq = 0;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    all: [],
    info: {},
    zlist: [],
    luyin: false
  },

  _Getall: function () {
    return new Promise((succ, err) => {
      s.se("nandu", nandu);
      s.g("p/getceshi", {
        s: (d) => {
          if (d.code == 200) {
            this.setData({
              all: d.data
            })
            succ();
          }
        }
      })
    })
  },

  _Langdu: function (e) {
    let text = e.currentTarget.dataset.for;
    app.baidutoken().then((token) => {
      const innerAudioContext = wx.createInnerAudioContext({
        useWebAudioImplement: false
      })
      innerAudioContext.src = "http://tsn.baidu.com/text2audio?lan=zh&ctp=1&cuid=abcdxxx&tok=" + token + "&tex=" + text + "&vol=9&per=0&spd=5&pit=5&aue=3"
      innerAudioContext.play();
    })
  },

  _Init: function () {
    let info = this.data.all[nowidx];
    this.setData({
      info,
      luyin:false
    })
    if (info.fenlei == '听音选字') {
      s.se("nandu", nandu);
      s.se("zi", info.neirong);
      s.g("p/getxuanzilist", {
        s: (d) => {
          if (d.code == 200) {
            let list = d.data.map((o) => {
              return o.zi;
            })
            list.push(info.neirong);
            this.setData({
              zlist: list.sort(() => {
                return Math.random() - 0.5;
              })
            })
          }
        }
      })
    }

  },

  _Xuanzi: function (e) {
    let choose = e.currentTarget.dataset.for;
    app.tm('是否确认选择', () => {
      if (choose == this.data.info.neirong) {
        app.ts("正确");
        zq++;
      } else {
        app.te("错误，答案为：" + this.data.info.neirong);
      }
      setTimeout(() => {
        this._Next();
      }, 1000);
    })
  },

  _Chulires: function (text) {
    if (text == this.data.info.neirong) {
      app.ts("读音正确");
      zq++;
      this.setData({
        luyin:true
      })
    } else {
      app.te("读音错误");
      this.setData({
        luyin:true
      })
    }
  },


  _Next: function () {
    let final = false;
    let all = this.data.all;
    if(all.length <= 10){
      if(all.length == nowidx+1){
        final = true;
      }
    }else{
      if(nowidx == 9){
        final = true;
      }
    }
    if(final){
      let fenshu = ~ ~(zq*100/all.length);
      app.ts("你的得分为："+fenshu,()=>{
        s.se("fenshu",fenshu);
        s.sb("ceshi");
        s.si('uid');
        s.se("nandu",nandu);
        s.g("c/info_charu",{
          s:(d)=>{
            if(d.code == 200){
              if(fenshu >= 0 && nandu!='高'){
                //解锁
                s.si("uid");
                s.g("p/jiesuo",{
                  s:(d)=>{
                    wx.navigateBack()
                  }
                })
              }else{
                wx.navigateBack()
              }
            }
          }
        })
      })
    }else{
      nowidx++;
      this._Init();
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let n = options.n || 0;
    nandu = ['入门', '低', '中', '高'][n];
    this._Getall().then(() => {
      this._Init();
    })
    recorderManager.onStop((res) => {
      // 停止录音  
      this.stopRecording(res.tempFilePath);
    });
  },

  startRecording() {
    recorderManager.start({
      format: 'wav',
      sampleRate: 16000,
      numberOfChannels: 1,
      success: res => {
        console.log('开始录音', res);
      },
      fail: err => {
        console.error('录音失败', err);
      }
    });
    app.ts("开始录音");
  },

  StopLuyin: function () {
    recorderManager.stop();
  },

  // 停止录音并转换语音为文字  
  stopRecording(tempFilePath) {
    // 将录音文件转换为文字  
    console.log(tempFilePath)
    let that = this;
    app.baidutoken().then((token) => {
      const fs = wx.getFileSystemManager();
      fs.readFile({ //读取文件并转为ArrayBuffer
        filePath: tempFilePath,
        success(res) {
          const base64 = wx.arrayBufferToBase64(res.data);
          var fileSize = res.data.byteLength;
          wx.request({
            url: 'https://vop.baidu.com/server_api',
            data: {
              format: 'wav',
              rate: 16000,
              channel: 1,
              cuid: 'sdfdfdfsfs',
              token: token,
              speech: base64,
              len: fileSize
            },
            method: 'POST',
            header: {
              'content-type': 'application/json' // 默认值
            },
            success(res) {
              wx.hideLoading();
              console.log(res.data);
              var result = res.data.result;
              if (result.length == 0) {
                wx.showToast({
                  title: "未识别到语音信息!",
                  icon: 'none',
                  duration: 3000
                })
                return;
              }
              var keyword = result[0];
              keyword = keyword.replace("。", "");
              that._Chulires(keyword);
            }
          })
        }
      })
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})